package com.telephone.purchase.controller;

import com.alibaba.fastjson.JSON;
import com.telephone.purchase.entity.LoginUser;
import com.telephone.purchase.service.impl.LoginLoginUserServiceImpl;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by unicom on 2019/8/29.
 */

@RestController
@RequestMapping("/hfgo")
public class LoginUserController {
    @Autowired
    private LoginLoginUserServiceImpl UserService;

    @RequestMapping("/saveuser")
    @CrossOrigin(origins = "http://localhost:8096",allowCredentials = "true")
    @ResponseBody
    public String save(@RequestBody Map<String,Object> map) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword("retail_salt");
        try {
            System.out.println("开始注册=====>loginUser:" +

            "--phone:" + map.get("phoneNumber")+
            "--email:" + map.get("userEmail")+
            "--gender:" + map.get("userGender") +
            "--name:" + map.get("userName") +
            "--pwd:" + map.get("userPassword") +
            "--paypwd:" + map.get("payPassword")

            );
            LoginUser loginUser = new LoginUser();
//            判断性别
            if( map.get("userGender").toString().equals("male")  ){
                loginUser.setUserGender(1);
            }
            if( map.get("userGender").toString().equals("female") ){
                loginUser.setUserGender(0);
            }

            String pwd = textEncryptor.encrypt(map.get("userPassword").toString());
            String paypwd = textEncryptor.encrypt(map.get("payPassword").toString());

            loginUser.setUserPassword(pwd);
            loginUser.setPayPassword(paypwd);
            loginUser.setUserName(map.get("userName").toString());
            loginUser.setUserEmail(map.get("userEmail").toString());
            loginUser.setPhoneNumber(map.get("phoneNumber").toString());
            loginUser.setUserBalance("0");
            System.out.println("new Date==" + new Date());
            loginUser.setCreateTime(new Date());
            System.out.println("储蓄时间：" + loginUser.getCreateTime());

            try{
                UserService.save(loginUser);
            }catch (Exception e){
                System.out.println("error: " + e);
                String str = e.toString();
                List<String> list=new ArrayList<String>();
                Pattern p = Pattern.compile("(\\[[^\\]]*\\])");
                Matcher m = p.matcher(str);
                while(m.find()){
                    list.add(m.group().substring(1, m.group().length()-1));
                }
                System.out.println(list.get(1).toString());
                System.out.println(list.get(1).toString().equals("PHONE_NUMBER") );
                if (list.get(1).toString() .equals("PHONE_NUMBER")){
                    return "900";
                } else if (list.get(1).toString() .equals("USER_EMAIL")){
                    return "909";
                } else {
                    return "990";
                }

            }
            return "200";
        } catch (Exception e){
            return "400";
        }
    }

    @RequestMapping("/login")
    @CrossOrigin(origins = "http://localhost:8096",allowCredentials = "true")
    @ResponseBody
    public String login(@RequestBody Map<String,Object> map) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword("retail_salt");
        try {
            System.out.println("开始登陆====>loginUser:" +
                    "--loginAccount:" + map.get("loginAccount")+
                    "--loginPassword:" + map.get("loginPassword")
            );
            String loginAccount = map.get("loginAccount").toString();
            String loginPassword = map.get("loginPassword").toString();

            LoginUser loginUser;

            if (loginAccount.contains("@")){
                loginUser = UserService.findUserByEmail(loginAccount);
            } else {
                loginUser = UserService.findUserByPhone(loginAccount);
            }

            System.out.println("usr:" + loginUser.getUserName());
            String OriginPwd = textEncryptor.decrypt(loginUser.getUserPassword().toString());
            System.out.println("OriginPwd:" + OriginPwd);
            System.out.println("loginPassword:" + loginPassword);
            System.out.println(loginPassword.equals(OriginPwd));
            if (loginPassword.equals(OriginPwd)){

                Long userId = loginUser.getId();
                int roleId = loginUser.getRoleId();
                String userName = loginUser.getUserName();
                System.out.println("用户数据：~~~ID== " + userId + "~~~ROLEID== "+ roleId + "~~~USERNAME== " + userName);
                System.out.println("======= 结束登陆 =======");
                return JSON.toJSONString(loginUser);

            } else {
                return "403";
            }
        } catch (Exception e){
            return "400";
        }
    }

    @RequestMapping("/postNewPwd")
    @CrossOrigin(origins = "http://localhost:8096",allowCredentials = "true")
    @ResponseBody
    public String postNewPwd(@RequestBody Map<String,Object> map) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword("retail_salt");
        try {

            System.out.println("开始修改密码====>user:" +
                    "--phoneNumber:" + map.get("phoneNumber")+
                    "--newPassword:" + map.get("newPassword")
            );
            String phoneNumber = map.get("phoneNumber").toString();
            String newPassword = map.get("newPassword").toString();

            String userPassword = textEncryptor.encrypt(newPassword);
            System.out.println("加密后密码：" + userPassword);
            String status = UserService.updatePassword(userPassword,phoneNumber);
            System.out.println("修改结果：" + status);

            return status;
        } catch (Exception e){
            return "400";
        }

    }


}



